<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use App\Models\LandingCompany;
use App\Services\BankService;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class TransactionController extends Controller
{
    protected $bankService;
    protected $smsService;

    public function __construct(BankService $bankService, SmsService $smsService)
    {
        $this->bankService = $bankService;
        $this->smsService = $smsService;
    }

    /**
     * 获取交易记录列表
     */
    public function index(Request $request)
    {
        $query = Transaction::with(['tenant', 'landingCompany', 'processedBy'])
            ->where('tenant_id', Auth::user()->tenant_id);

        // 搜索过滤
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('transaction_id', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // 交易类型过滤
        if ($request->filled('transaction_type')) {
            $query->where('transaction_type', $request->transaction_type);
        }

        // 状态过滤
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // 金额范围过滤
        if ($request->filled('min_amount')) {
            $query->where('amount', '>=', $request->min_amount);
        }
        if ($request->filled('max_amount')) {
            $query->where('amount', '<=', $request->max_amount);
        }

        // 时间范围过滤
        if ($request->filled('start_date')) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        // 排序
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        $transactions = $query->paginate($request->get('per_page', 15));

        return response()->json([
            'success' => true,
            'data' => $transactions
        ]);
    }

    /**
     * 获取交易记录详情
     */
    public function show($id)
    {
        $transaction = Transaction::with(['tenant', 'landingCompany', 'processedBy'])
            ->where('tenant_id', Auth::user()->tenant_id)
            ->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $transaction
        ]);
    }

    /**
     * 创建交易记录
     */
    public function store(Request $request)
    {
        $request->validate([
            'transaction_type' => ['required', Rule::in(['recharge', 'deduction', 'refund', 'settlement', 'withdrawal'])],
            'sub_type' => 'nullable|string|max:50',
            'amount' => 'required|numeric|min:0',
            'landing_company_id' => 'required|exists:landing_companies,id',
            'description' => 'nullable|string|max:500',
            'metadata' => 'nullable|array',
        ]);

        // 验证落地公司是否存在且为激活状态
        $landingCompany = LandingCompany::where('status', LandingCompany::STATUS_ACTIVE)
                                       ->findOrFail($request->landing_company_id);

        DB::beginTransaction();
        try {
            // 获取当前余额
            $currentBalance = $this->getCurrentBalance($landingCompany->id);
            
            // 计算新余额
            $newBalance = $this->calculateNewBalance(
                $currentBalance, 
                $request->amount, 
                $request->transaction_type
            );

            // 创建交易记录
            $transaction = Transaction::create([
                'transaction_id' => Transaction::generateTransactionId(),
                'tenant_id' => Auth::user()->tenant_id,
                'transaction_type' => $request->transaction_type,
                'sub_type' => $request->sub_type,
                'amount' => $request->amount,
                'balance_before' => $currentBalance,
                'balance_after' => $newBalance,
                'landing_company_id' => $request->landing_company_id,
                'status' => 'pending',
                'description' => $request->description,
                'metadata' => $request->metadata ?? [],
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '交易记录创建成功',
                'data' => $transaction->load(['tenant', 'landingCompany'])
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('创建交易记录失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '创建交易记录失败'
            ], 500);
        }
    }

    /**
     * 处理交易（确认/拒绝）
     */
    public function process($id, Request $request)
    {
        $request->validate([
            'action' => ['required', Rule::in(['approve', 'reject'])],
            'note' => 'nullable|string|max:500',
        ]);

        $transaction = Transaction::where('tenant_id', Auth::user()->tenant_id)
                                 ->where('status', 'pending')
                                 ->findOrFail($id);

        DB::beginTransaction();
        try {
            if ($request->action === 'approve') {
                // 处理银行转账（如果是提现或充值）
                if (in_array($transaction->transaction_type, ['withdrawal', 'recharge'])) {
                    $bankResult = $this->processBankTransaction($transaction);
                    
                    if (!$bankResult['success']) {
                        throw new \Exception('银行处理失败: ' . $bankResult['message']);
                    }
                    
                    $transaction->update([
                        'status' => 'processing',
                        'processed_by' => Auth::id(),
                        'processed_at' => now(),
                        'metadata' => array_merge($transaction->metadata ?? [], [
                            'bank_transaction_id' => $bankResult['transaction_id'],
                            'processing_note' => $request->note
                        ])
                    ]);
                } else {
                    $transaction->update([
                        'status' => 'completed',
                        'processed_by' => Auth::id(),
                        'processed_at' => now(),
                        'metadata' => array_merge($transaction->metadata ?? [], [
                            'processing_note' => $request->note
                        ])
                    ]);
                }
            } else {
                $transaction->update([
                    'status' => 'failed',
                    'processed_by' => Auth::id(),
                    'processed_at' => now(),
                    'metadata' => array_merge($transaction->metadata ?? [], [
                        'reject_reason' => $request->note
                    ])
                ]);
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => $request->action === 'approve' ? '交易已批准' : '交易已拒绝',
                'data' => $transaction->fresh(['tenant', 'landingCompany', 'processedBy'])
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('处理交易失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '处理交易失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 查询银行交易状态
     */
    public function checkBankStatus($id)
    {
        $transaction = Transaction::where('tenant_id', Auth::user()->tenant_id)
                                 ->findOrFail($id);

        $bankTransactionId = $transaction->metadata['bank_transaction_id'] ?? null;
        
        if (!$bankTransactionId) {
            return response()->json([
                'success' => false,
                'message' => '未找到银行交易ID'
            ], 400);
        }

        try {
            $statusResult = $this->bankService->queryTransferStatus($bankTransactionId);
            
            if ($statusResult['success']) {
                // 根据银行返回状态更新交易状态
                if ($statusResult['status'] === 'completed' && $transaction->status === 'processing') {
                    $transaction->update([
                        'status' => 'completed'
                    ]);
                } elseif ($statusResult['status'] === 'failed') {
                    $transaction->update([
                        'status' => 'failed',
                        'metadata' => array_merge($transaction->metadata ?? [], [
                            'bank_failure_reason' => $statusResult['message'] ?? '银行处理失败'
                        ])
                    ]);
                }

                return response()->json([
                    'success' => true,
                    'data' => [
                        'transaction' => $transaction->fresh(),
                        'bank_status' => $statusResult
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => '查询银行状态失败'
                ], 500);
            }

        } catch (\Exception $e) {
            Log::error('查询银行交易状态失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '查询银行状态失败'
            ], 500);
        }
    }

    /**
     * 获取交易统计数据
     */
    public function statistics(Request $request)
    {
        $tenantId = Auth::user()->tenant_id;
        
        // 时间范围
        $startDate = $request->get('start_date', now()->startOfMonth());
        $endDate = $request->get('end_date', now()->endOfMonth());

        $query = Transaction::where('tenant_id', $tenantId)
                           ->whereBetween('created_at', [$startDate, $endDate]);

        // 总体统计
        $totalStats = [
            'total_count' => $query->count(),
            'total_amount' => $query->sum('amount'),
            'completed_count' => $query->where('status', 'completed')->count(),
            'completed_amount' => $query->where('status', 'completed')->sum('amount'),
            'pending_count' => $query->where('status', 'pending')->count(),
            'pending_amount' => $query->where('status', 'pending')->sum('amount'),
        ];

        // 按类型统计
        $typeStats = Transaction::where('tenant_id', $tenantId)
                               ->whereBetween('created_at', [$startDate, $endDate])
                               ->selectRaw('transaction_type, COUNT(*) as count, SUM(amount) as total_amount')
                               ->groupBy('transaction_type')
                               ->get();

        // 按日期统计（最近30天）
        $dailyStats = Transaction::where('tenant_id', $tenantId)
                                ->whereBetween('created_at', [now()->subDays(30), now()])
                                ->selectRaw('DATE(created_at) as date, COUNT(*) as count, SUM(amount) as total_amount')
                                ->groupBy('date')
                                ->orderBy('date')
                                ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'total_stats' => $totalStats,
                'type_stats' => $typeStats,
                'daily_stats' => $dailyStats
            ]
        ]);
    }

    /**
     * 批量处理交易
     */
    public function batchProcess(Request $request)
    {
        $request->validate([
            'transaction_ids' => 'required|array|min:1',
            'transaction_ids.*' => 'exists:transactions,id',
            'action' => ['required', Rule::in(['approve', 'reject'])],
            'note' => 'nullable|string|max:500',
        ]);

        $transactions = Transaction::where('tenant_id', Auth::user()->tenant_id)
                                  ->where('status', 'pending')
                                  ->whereIn('id', $request->transaction_ids)
                                  ->get();

        if ($transactions->count() !== count($request->transaction_ids)) {
            return response()->json([
                'success' => false,
                'message' => '部分交易记录不存在或状态不正确'
            ], 400);
        }

        DB::beginTransaction();
        try {
            $results = [];
            
            foreach ($transactions as $transaction) {
                if ($request->action === 'approve') {
                    $transaction->update([
                        'status' => 'completed',
                        'processed_by' => Auth::id(),
                        'processed_at' => now(),
                        'metadata' => array_merge($transaction->metadata ?? [], [
                            'batch_processing_note' => $request->note
                        ])
                    ]);
                } else {
                    $transaction->update([
                        'status' => 'failed',
                        'processed_by' => Auth::id(),
                        'processed_at' => now(),
                        'metadata' => array_merge($transaction->metadata ?? [], [
                            'batch_reject_reason' => $request->note
                        ])
                    ]);
                }
                
                $results[] = $transaction->fresh();
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '批量处理完成',
                'data' => $results
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('批量处理交易失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '批量处理失败'
            ], 500);
        }
    }

    /**
     * 获取当前账户余额
     */
    private function getCurrentBalance($landingCompanyId)
    {
        $lastTransaction = Transaction::where('landing_company_id', $landingCompanyId)
                                    ->where('status', 'completed')
                                    ->orderBy('created_at', 'desc')
                                    ->first();

        return $lastTransaction ? $lastTransaction->balance_after : 0;
    }

    /**
     * 计算新余额
     */
    private function calculateNewBalance($currentBalance, $amount, $transactionType)
    {
        switch ($transactionType) {
            case 'recharge':
                return $currentBalance + $amount;
            case 'deduction':
            case 'withdrawal':
                return $currentBalance - $amount;
            case 'refund':
                return $currentBalance + $amount;
            case 'settlement':
                return $currentBalance - $amount;
            default:
                return $currentBalance;
        }
    }

    /**
     * 处理银行交易
     */
    private function processBankTransaction($transaction)
    {
        try {
            if ($transaction->transaction_type === 'withdrawal') {
                // 提现：从系统账户转出到用户账户
                return $this->bankService->transfer([
                    'amount' => $transaction->amount,
                    'recipient_account' => $transaction->landingCompany->account_number,
                    'recipient_name' => $transaction->landingCompany->account_name,
                    'purpose' => '提现',
                    'reference' => $transaction->transaction_id
                ]);
            } elseif ($transaction->transaction_type === 'recharge') {
                // 充值：从用户账户转入到系统账户
                return $this->bankService->transfer([
                    'amount' => $transaction->amount,
                    'sender_account' => $transaction->landingCompany->account_number,
                    'sender_name' => $transaction->landingCompany->account_name,
                    'purpose' => '充值',
                    'reference' => $transaction->transaction_id
                ]);
            }
            
            return ['success' => true, 'transaction_id' => 'MOCK_' . uniqid()];
            
        } catch (\Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
}